package com.wan.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import com.reyun.sdk.ReYunTrack;
//import com.reyun.sdk.TrackingIO;
import com.wan.activity.util.EditTextFocusLintener;
import com.wan.commonsdk.Conet;
import com.wan.commonsdk.HttpUtils;
import com.wan.commonsdk.MD5Utils;
import com.wan.commonsdk.WanCommonSdk;
import com.wan.commonsdk.WanServerResposeCode;

import net.sourceforge.simcpux.Util;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class WanPhoneRegesterActivity extends BaseActivity implements
		OnClickListener {
	private EditText phone_reges_number, phone_code, phone_reg_password;
	private TextView phone_time_tx;
	private Button phone_bootom_btn;
	private TimeCount time;
	private final int REGESTER_SUCCESS = WanServerResposeCode.WAN_REGESTER_SUCCESS;
	private final int PHONE_REG_SUCC = 1;
	private final int PHONE_REG_FAIL_PW = -2;
	private final int NETWORK_ERROR = 10086;
	private final int REGREEOR = -100;
	String phone_num, password;
	private Button phone_reg_back;
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case -1:
				hideLoading();
				time.cancel();
				time.onFinish();
				break;
			case REGESTER_SUCCESS:
				hideLoading();
				Toast.makeText(getApplicationContext(), "收到验证码后请填写",
						Toast.LENGTH_SHORT).show();
				break;
			case PHONE_REG_SUCC:
				HashMap<String, String> map = (HashMap<String, String>) msg.obj;
				Conet.mUserInfo.setAccess_token(map.get("token"));
				Conet.mUserInfo.setBind_Phone(phone_num);
				Conet.mUserInfo.setGuest(false);
				Conet.mUserInfo.setUser_id(map.get("userid"));
				Conet.mUserInfo.setUser_password(password);
				Conet.mUserInfo.setUser_name(phone_num);
				
//				TrackingIO.setRegisterWithAccountID(Conet.mUserInfo
//						.getUser_id());
//				TrackingIO
//						.setLoginSuccessBusiness(Conet.mUserInfo.getUser_id());
				
				ReYunTrack.setRegisterWithAccountID(Conet.mUserInfo
						.getUser_id());
				ReYunTrack
						.setLoginSuccessBusiness(Conet.mUserInfo.getUser_id());
				WanCommonSdk.loginCallBack.loginSuccess(
						Conet.mUserInfo.getUser_id(),
						Conet.mUserInfo.getAccess_token());
				Conet.getInstance().exit();
				finish();
				break;
			case PHONE_REG_FAIL_PW:
				Toast.makeText(getApplicationContext(), "帐号或密码格式不正确，请重新输入",
						Toast.LENGTH_SHORT).show();
				break;
			case -3:
				hideLoading();
				time.cancel();
				time.onFinish();
				Toast.makeText(getApplicationContext(), "手机号已注册",
						Toast.LENGTH_SHORT).show();
				break;
			case 806:
				hideLoading();
				time.cancel();
				time.onFinish();
				Toast.makeText(getApplicationContext(), "手机号与验证码不匹配！",
						Toast.LENGTH_SHORT).show();
				break;
			case -100:
				hideLoading();
				time.cancel();
				time.onFinish();
				Toast.makeText(getApplicationContext(), "注册失败！",
						Toast.LENGTH_SHORT).show();
				break;

			}

		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(Util.getResID("wan51_preg_layout", "layout"));
		init();
	}

	private void init() {
		phone_reges_number = (EditText) findViewById(Util.getResID(
				"phone_reges_number", "id"));
		phone_code = (EditText) findViewById(Util.getResID("phone_code", "id"));
		phone_reg_password = (EditText) findViewById(Util.getResID(
				"phone_reg_password", "id"));
		phone_time_tx = (TextView) findViewById(Util.getResID("phone_time_tx",
				"id"));
		phone_time_tx.setOnClickListener(this);
		phone_bootom_btn = (Button) findViewById(Util.getResID(
				"phone_bootom_btn", "id"));
		phone_bootom_btn.setOnClickListener(this);
		time = new TimeCount(60000, 1000);
		phone_reg_back = (Button) findViewById(Util.getResID("phone_reg_back",
				"id"));
		phone_reg_back.setOnClickListener(this);

		Button phone_un_edclose = (Button) findViewById(Util.getResID(
				"phone_un_edclose", "id"));
		Button phone_reg_password_close = (Button) findViewById(Util.getResID(
				"phone_reg_password_close", "id"));
		phone_reges_number.setOnFocusChangeListener(new EditTextFocusLintener(
				phone_reges_number, phone_un_edclose));

		phone_reg_password.setOnFocusChangeListener(new EditTextFocusLintener(
				phone_reg_password, phone_reg_password_close));
	}

	private Boolean checkPhone() {
		int un_length = this.phone_reges_number.getText().toString().length();

		Pattern pattern = Pattern.compile("[0-9]*");
		Boolean num = pattern.matcher(
				this.phone_reges_number.getText().toString()).matches();
		if (un_length == 0) {
			Toast.makeText(getApplicationContext(),
					this.getString(Util.getResID("mobile_phone", "string")),
					Toast.LENGTH_SHORT).show();

			return false;
		}
		if (un_length != 11 && num) {
			Toast.makeText(
					getApplicationContext(),
					this.getString(Util
							.getResID("mobile_phone_wrong", "string")),

					Toast.LENGTH_SHORT).show();
			return false;
		}

		return true;
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == Util.getResID("phone_time_tx", "id")) {
			phone_num = phone_reges_number.getText().toString();
			if (checkPhone()) {

				showLoading();
				PhoneCodeTask phoneCT = new PhoneCodeTask(phone_num);
				phoneCT.execute();
				time.start();
			}
		} else if (v.getId() == Util.getResID("phone_bootom_btn", "id")) {
			phone_num = phone_reges_number.getText().toString();
			String phone_code_tx = phone_code.getText().toString();
			password = phone_reg_password.getText().toString();
			PhoneRegesTask phoneres = new PhoneRegesTask();
			phoneres.execute();

		} else if (v.getId() == Util.getResID("phone_reg_back", "id")) {
			finish();
		}
	}

	// ------------------------------------------------------------------------
	// 倒计时处理类
	//
	//
	// ------------------------------------------------------------------------

	class TimeCount extends CountDownTimer {
		public TimeCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
		}

		@Override
		public void onFinish() {// 计时完毕时触发
			phone_time_tx.setText("重新验证");

			// btn_getcode.setBackground(getResources().getDrawable(R.drawable.btn_login_se));
			phone_time_tx.setClickable(true);
			phone_time_tx.setBackgroundResource(Util.getResID(
					"wan51_login_bg_down", "drawable"));
		}

		@Override
		public void onTick(long millisUntilFinished) {// 计时过程显示
			phone_time_tx.setClickable(false);
			// btn_getcode.setBackgroundColor(0xcccccc);
			phone_time_tx.setText(millisUntilFinished / 1000 + "秒");
			phone_time_tx.setBackgroundResource(Util.getResID(
					"wan51_send_code", "drawable"));
		}
	}

	class PhoneCodeTask extends AsyncTask {
		private String _phoneNumber;

		public PhoneCodeTask(String _phoneNumber) {
			this._phoneNumber = _phoneNumber;
		}

		@Override
		protected Object doInBackground(Object... params) {
			boolean isreq = false;
			HashMap<String, String> result = new HashMap<String, String>();
			HttpGet httpGet = new HttpGet(Conet.PhoneCheckUrl + phone_num);
			try {
				HttpResponse httpResponse = new DefaultHttpClient()
						.execute(httpGet);
				if (httpResponse.getStatusLine().getStatusCode() == 200) {
					String strResult = EntityUtils.toString(
							httpResponse.getEntity(), "UTF-8");
					isreq = Boolean.parseBoolean(strResult);

				}
			} catch (Exception e) {
				e.printStackTrace();
				result = null;
			}
			if (isreq) {
				result = HttpUtils.HttpSendCode("-1", "bind", _phoneNumber);
			} else if (!isreq) {
				result.put("noreq", "-3");
			}

			return result;
		}

		@Override
		protected void onPostExecute(Object result) {

			HashMap<String, String> resultm = (HashMap<String, String>) result;
			Message msg = mHandler.obtainMessage();
			if (resultm == null) {
				mHandler.obtainMessage(NETWORK_ERROR).sendToTarget();
				return;
			} else if ("-3".equals(resultm.get("noreq"))) {
				msg.what = -3;
				mHandler.sendMessage(msg);
			} else if (resultm.get("status").equals(
					String.valueOf(REGESTER_SUCCESS))) {
				msg.what = REGESTER_SUCCESS;
				mHandler.sendMessage(msg);
			} else {

				msg.what = -1;
				mHandler.sendMessage(msg);
			}
		}
	}

	class PhoneRegesTask extends AsyncTask {
		@Override
		protected Object doInBackground(Object... params) {
			HashMap<String, String> map = new HashMap<String, String>();
			String phone_num = phone_reges_number.getText().toString();
			String phone_code_tx = phone_code.getText().toString();
			String password = phone_reg_password.getText().toString();

			HttpPost httpRequest = new HttpPost(Conet.PhoneRegesterUrl);
			List<NameValuePair> listparams = new ArrayList<NameValuePair>();
			listparams.add(new BasicNameValuePair("username", phone_num));
			listparams.add(new BasicNameValuePair("password", password));
			listparams.add(new BasicNameValuePair("client_id",
					Conet.mWanAppInfo.getAppId()));
			// listparams.add(new BasicNameValuePair("who", Util.getAdID()));
			// listparams.add(new BasicNameValuePair("whotype", "6"));
			String whotype = "3";
			if (Integer.parseInt(Conet.who) > 50000) {
				whotype = "6";
			}
			listparams.add(new BasicNameValuePair("who", Conet.who));
			listparams.add(new BasicNameValuePair("whotype", whotype));
			listparams.add(new BasicNameValuePair("code", phone_code_tx));
			String sign = MD5Utils.getMD5(phone_num + password
					+ Conet.mWanAppInfo.getAppSecret());
			listparams.add(new BasicNameValuePair("sign", sign));

			DefaultHttpClient httpclient = new DefaultHttpClient();
			// httpclient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT,
			// SO_TIMEOUT);
			// httpclient.getParams().setIntParameter(
			// HttpConnectionParams.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);

			try {
				Util.LogUtil("HttpExecute-----conn----");
				httpRequest.setEntity(new UrlEncodedFormEntity(listparams,
						HTTP.UTF_8));
				HttpResponse httpResponse = httpclient.execute(httpRequest);
				if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

					// StringBuilder builder = new StringBuilder();

					String result = EntityUtils.toString(httpResponse
							.getEntity());
					JSONObject jsonObject = new JSONObject(result);
					String code = jsonObject.optString("code");
					map.put("code", code);
					if ("0".equals(code)) {
						jsonObject = jsonObject.optJSONObject("data");
						String userid = jsonObject.optString("userid");
						String token = jsonObject.optString("token");
						map.put("userid", userid);
						map.put("token", token);
					}

				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return map;

		}

		@Override
		protected void onPostExecute(Object result) {
			// TODO Auto-generated method stub
			HashMap<String, String> map = (HashMap<String, String>) result;
			String code = map.get("code");
			Message msg = mHandler.obtainMessage();
			if ("0".equals(code)) {
				msg.what = PHONE_REG_SUCC;
				msg.obj = map;
			} else if ("201".equals(code) || "202".equals(code)
					|| "501".equals(code) || "502".equals(code)) {

				msg.what = PHONE_REG_FAIL_PW;
			} else if ("100".equals(code)) {
				msg.what = -3;
			} else if ("806".equals(code)) {
				msg.what = 806;
			} else {
				msg.what = -100;
			}
			mHandler.sendMessage(msg);
		}
	}
}
